import threading
import time
import tkinter as tk
import asyncio



# loop = asyncio.get_event_loop()

# MyThread(update_label, root, label)
class MyThread(threading.Thread):
    def __init__(self, func, *args):
        super().__init__()

        self.func = func
        self.args = args

        # self.setDaemon(True)
        self.start()  # 在这里开始

    def run(self):
        self.func(*self.args)

def download():
    # 模拟下载任务，这里可以替换为实际的下载操作
    maxI=10
    for i in range(1, maxI):
        result_label.config(text=f"下载中... ({i}/{maxI})")
        root.update()  # 更新主界面以显示下载进度
        time.sleep(2)  # 模拟下载延迟
        # for j in range(1, 10):
        #     for k in range(1, 99):
        #         for l in range(1, 99):
        #             pass
                    # """"""
            # print(j)
    result_label.config(text="下载完成")

root = tk.Tk()
root.title("多线程示例")
root.geometry("300x300")

download_button = tk.Button(root, text="开始下载", command=download)
download_button.pack()

result_label = tk.Label(root, text="")
result_label.pack()

#处理线程,避免UI卡死
action_thread = None

def start_action_thread():
    global action_thread
    if action_thread is None or not action_thread.is_alive():
        action_thread = threading.Thread(target=download)
        action_thread.start()
        
download_button = tk.Button(root, text="开始下载(异步)", command=start_action_thread)
download_button.pack()

download_button = tk.Button(root, text="开始下载(MyThread异步)", command=lambda:MyThread(download))
download_button.pack()

root.mainloop()

